package cn.wolfcode.mq;

import cn.wolfcode.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by wolfcode-lanxw
 */
@Component
@RocketMQMessageListener(consumerGroup = "OrderMQListener", topic = MQConstants.ORDER_RESULT_TOPIC)
@Slf4j
public class OrderMQListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult message) {
        try {
            System.out.println("订单结果......" + message);

            TimeUnit.MILLISECONDS.sleep(2000); // 睡眠2秒

            WebSocketServer ws = WebSocketServer.clients.get(message.getToken());
            if (ws == null) {
                log.error("对应token的用户未登陆......" + message.getToken());
            }
            // 可以通过这个uuid获取到客户端对象.
            ws.getSession().getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (Exception e) {
            e.printStackTrace();
            // 通知不到用户,对整体的业务没有影响.用户还可以在《我的订单》看到是否创建了订单.
        }
    }
}
